package org.eiahe.hr.performance.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.exception.ServiceException;
import org.ehe.common.core.utils.SpringUtils;
import org.eiahe.hr.performance.domain.PerformanceCycle;
import org.eiahe.hr.performance.domain.PerformanceResult;
import org.eiahe.hr.performance.domain.PerformanceScoreDetail;
import org.eiahe.hr.performance.mapper.PerformanceCycleMapper;
import org.eiahe.hr.performance.mapper.PerformanceResultMapper;
import org.eiahe.hr.performance.mapper.PerformanceScoreDetailMapper;
import org.eiahe.hr.performance.service.IPerformanceCycleService;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 绩效考核周期Service业务层处理
 *
 * @author zhangnn
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PerformanceCycleServiceImpl implements IPerformanceCycleService {

    private final PerformanceCycleMapper baseMapper;

    @Override
    public PerformanceCycle queryById(Long cycleId) {
        return baseMapper.selectById(cycleId);
    }

    @Override
    public List<PerformanceCycle> queryList(PerformanceCycle cycle) {
        LambdaQueryWrapper<PerformanceCycle> lqw = buildQueryWrapper(cycle);
        return baseMapper.selectList(lqw);
    }

    @Override
    public TableDataInfo<PerformanceCycle> queryPageList(PerformanceCycle cycle, PageQuery pageQuery) {
        LambdaQueryWrapper<PerformanceCycle> lqw = buildQueryWrapper(cycle);
        Page<PerformanceCycle> page = baseMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    private LambdaQueryWrapper<PerformanceCycle> buildQueryWrapper(PerformanceCycle cycle) {
        LambdaQueryWrapper<PerformanceCycle> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(cycle.getCycleName()), PerformanceCycle::getCycleName, cycle.getCycleName());
        lqw.eq(StringUtils.isNotBlank(cycle.getCycleType()), PerformanceCycle::getCycleType, cycle.getCycleType());
        lqw.eq(StringUtils.isNotBlank(cycle.getStatus()), PerformanceCycle::getStatus, cycle.getStatus());
        lqw.eq(StringUtils.isNotBlank(cycle.getDelFlag()), PerformanceCycle::getDelFlag, cycle.getDelFlag());
        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PerformanceCycle cycle) {
        return baseMapper.insert(cycle) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(PerformanceCycle cycle) {
        return baseMapper.updateById(cycle) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        if (isValid) {
            // 校验逻辑可以根据需要添加
            // 校验1：检查是否有正在进行的考核
            LambdaQueryWrapper<PerformanceCycle> checkLqw = Wrappers.lambdaQuery();
            checkLqw.in(PerformanceCycle::getCycleId, ids);
            checkLqw.eq(PerformanceCycle::getStatus, "1"); // 进行中
            List<PerformanceCycle> activeCycles = baseMapper.selectList(checkLqw);

            if (CollUtil.isNotEmpty(activeCycles)) {
                String names = activeCycles.stream()
                    .map(PerformanceCycle::getCycleName)
                    .collect(Collectors.joining(", "));
                throw new ServiceException("以下考核周期正在进行中，无法删除：" + names);
            }

            // 校验2：检查是否已被绩效结果引用
            PerformanceResultMapper resultMapper = SpringUtils.getBean(PerformanceResultMapper.class);
            LambdaQueryWrapper<PerformanceResult> resultLqw = Wrappers.lambdaQuery();
            resultLqw.in(PerformanceResult::getCycleId, ids);
            resultLqw.eq(PerformanceResult::getDelFlag, "0");
            long count = resultMapper.selectCount(resultLqw);

            if (count > 0) {
                throw new ServiceException("该周期已被" + count + "条绩效结果使用，无法删除");
            }

            // 校验3：检查是否有关联的评分明细（逻辑删除）
            PerformanceScoreDetailMapper detailMapper = SpringUtils.getBean(PerformanceScoreDetailMapper.class);
            LambdaQueryWrapper<PerformanceScoreDetail> detailLqw = Wrappers.lambdaQuery();
            detailLqw.in(PerformanceScoreDetail::getResultId, ids); // 假设resultId关联cycleId
            List<PerformanceScoreDetail> details = detailMapper.selectList(detailLqw);

            if (CollUtil.isNotEmpty(details)) {
                // 将关联的评分明细标记为删除
                List<Long> detailIds = details.stream()
                    .map(PerformanceScoreDetail::getDetailId)
                    .collect(Collectors.toList());
                detailMapper.deleteBatchIds(detailIds);
                log.warn("级联删除评分明细：{}条", detailIds.size());
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
